package com.happyass.config.shiro;

import com.happyass.dao.StaffDao;
import com.happyass.pojo.Staff;
import com.happyass.service.StaffInfoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

//import com.thornbird.tmall.modules.account.entity.Resource;
//import com.thornbird.tmall.modules.account.entity.Role;
//import com.thornbird.tmall.modules.account.entity.User;
//import com.thornbird.tmall.modules.account.service.ResourceService;
//import com.thornbird.tmall.modules.account.service.RoleService;
//import com.thornbird.tmall.modules.account.service.UserService;

@Component
public class MyRealm extends AuthorizingRealm {
	
	@Autowired
	private StaffInfoService staffInfoService;
	@Autowired
	private StaffDao staffDao;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Staff staff = (Staff) principals.fromRealm(this.getName()).iterator().next();
		System.err.println("开始给用户"+staff.getStaffUsername()+"授权");
		List<String> listRole = staffDao.searchRole(staff.getStaffUsername());
		List<String> listPermission = staffDao.searchPermission(staff.getStaffUsername());
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.addRoles(listRole);
		simpleAuthorizationInfo.addStringPermissions(listPermission);
		for (String s :listRole) {
			System.err.println("赋予角色"+listRole);
		}
		for (String s :listPermission) {
			System.err.println("赋予权限"+listPermission);
		}
		return simpleAuthorizationInfo;

	}



	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String staffName = (String) token.getPrincipal();
		Staff staff = staffInfoService.getStaffByStaffUserName(staffName);

		// 身份验证器，包装用户名和密码
		return new SimpleAuthenticationInfo(staff, staff.getStaffPwd(),getName());
	}


}
